package com.tencent.welink.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created by junchihe on 2018/5/21.
 */
public class AES128 implements IEncryptAndDecrypt{
    private static final Logger log = LogManager.getLogger(AES128.class);
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    Cipher cipher = null;
    Cipher cipherDecrypt = null;

    public AES128(String password) {
        this(password, 128,true, false);
    }

    public AES128(String password, int passwordInitLen, boolean useEn,boolean useDe) {
        try {
            if(useEn) {
                cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
                cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password, passwordInitLen));// 初始化为加密模式的密码器
            }
            if (useDe) {
                cipherDecrypt = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
                cipherDecrypt.init(Cipher.DECRYPT_MODE, getSecretKey(password, passwordInitLen));
            }
        }catch ( Exception e) {
            log.error("AES128 Construct error:",e);
        }
    }

    @Override
    public  byte[] encrypt(byte[] content )  {
        try {
            return cipher.doFinal(content);// 加密
        }catch ( Exception e) {
           log.error(e);
        }
        return null;
    }

    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    @Override
    public  String encrypt(String content ) {
        try {
            byte[] byteContent = content.getBytes("utf-8");
            byte[] result = encrypt(byteContent);// 加密
            if(result == null) return null;
            return Base64.encodeBase64String(result);//通过Base64转码返回
        } catch (Exception ex) {
            log.error( ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    @Override
    public String decrypt(String content ) {

        try {

            byte[] result = decrypt(Base64.decodeBase64(content));
            if(result == null) return null;
            return new String(result, "utf-8");
        } catch (Exception ex) {
            log.error(ex);
        }

        return null;
    }

    @Override
    public byte[] decrypt(byte[] content) {

        try {

            return cipherDecrypt.doFinal(content);
        } catch (Exception ex) {
            log.error(ex);
        }

        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password,final int passwordInitLen) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;

        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            // 根据密钥初始化密钥生成器
            kg.init(passwordInitLen, secureRandom);
            //AES 要求密钥长度为 128
           //kg.init(passwordInitLen, new SecureRandom(password.getBytes()));
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();

            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
        } catch (NoSuchAlgorithmException ex) {
           log.error(ex);
        }

        return null;
    }



    public static void main(String[] args)throws  Exception {
        System.out.println("===========================");
        String s = "hello,643213";

        System.out.println("s:" + s);
        int passwordInitLen = 128;
        AES128 aes = new AES128("123456");
        //passwordInitLen = 256;
        AES128 aes2 = new AES128("12345689",passwordInitLen,true,true);
        String s1 = aes.encrypt(s);
        System.out.println("s1:" + s1);

        System.out.println("s2:"+ aes.decrypt(s1));



        byte[] s12w = aes2.encrypt(s.getBytes());
        System.out.println("s12:" + s12w.length);

        System.out.println("s22:"+ aes2.decrypt(s12w).length);


        byte[] s12e = aes2.encrypt("hello,645213".getBytes());
        System.out.println("s12:" + s12e.length);

        System.out.println("s22:"+ aes2.decrypt(s12e));
        System.out.println("===========================");

    }
}
